package com.my.system.dao.order;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.my.system.dao.DataBaseConnection;
import com.my.system.object.order.Payment;

public class PayMentDao {
	private static Connection con = null;
	private static PreparedStatement psta = null;
	private static ResultSet rs = null;
	static {
		con = DataBaseConnection.getConnection();
	}

	public static boolean insertPayment(Payment payment) {
		String sql = "insert into payment(order_id," + "payment_status_id"
				+ ")values(?,?)";
		try {
			psta = con.prepareStatement(sql);
			psta.setInt(1, payment.getOrder_id());
			psta.setInt(2, payment.getPayment_status_id());
			con.setAutoCommit(false);
			int i = psta.executeUpdate();
			con.commit();
			con.setAutoCommit(true);
			if (i > 0) {
				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				if (psta != null) {
					psta.close();
				}
				if (rs != null) {
					psta.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return false;
	}
	
	
	public static boolean updatePayment(Payment payment) {
		String sql = "update payment set payment_status_id=? where id=?";
		try {
			psta = con.prepareStatement(sql);
			psta.setInt(1, payment.getPayment_status_id());
			psta.setInt(2, payment.getId());
			con.setAutoCommit(false);
			int i = psta.executeUpdate();
			con.commit();
			con.setAutoCommit(true);
			if (i > 0) {
				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			try {
				con.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				if (psta != null) {
					psta.close();
				}
				if (rs != null) {
					psta.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return false;
	}

	public static Payment searchByOrderId(int id) {
		String sql = "select * from payment where order_id=? and payment_status_id=?";
		try {
			psta = con.prepareStatement(sql);
			psta.setInt(1, id);
			psta.setInt(2, 2);
			rs = psta.executeQuery();
			if (rs.next()) {
				int id1 = rs.getInt(1);
				int order_id = rs.getInt(2);
				int payment_status_id = rs.getInt(3);
				return new Payment(id1, order_id, payment_status_id);
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		} finally {
			try {
				if (psta != null) {
					psta.close();
				}
				if (rs != null) {
					psta.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;
	}

}
